package com.item.service;

import com.item.dao.CodeMapper;
import com.item.dao.model.Code;
import com.item.dao.model.CodeExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CodeService {
    @Autowired
    private CodeMapper codeMapper;

    private Map<String,Code> codeMap;

    public int countByExample(CodeExample example) {
        return this.codeMapper.countByExample(example);
    }

    public Code selectByPrimaryKey(String code) {
        return this.codeMapper.selectByPrimaryKey(code);
    }

    public List<Code> selectByExample(CodeExample example) {
        return this.codeMapper.selectByExample(example);
    }

    public int deleteByPrimaryKey(String code) {
        codeMap = null;
        return codeMapper.deleteByPrimaryKey(code);
    }

    public int updateByPrimaryKeySelective(Code record) {
        codeMap = null;
        return codeMapper.updateByPrimaryKeySelective(record);
    }
    
    public int updateByPrimaryKey(Code record) {
        codeMap = null;
        return codeMapper.updateByPrimaryKey(record);
    }

    public int deleteByExample(CodeExample example) {
        codeMap = null;
        return codeMapper.deleteByExample(example);
    }

    public int updateByExampleSelective(Code record, CodeExample example) {
        codeMap = null;
        return codeMapper.updateByExampleSelective(record, example);
    }

    public int updateByExample(Code record, CodeExample example) {
        codeMap = null;
        return codeMapper.updateByExample(record, example);
    }

    public int insert(Code record) {
        return codeMapper.insert(record);
    }

    public int insertSelective(Code record) {
        return codeMapper.insertSelective(record);
    }
    
    public String getCode(String code){
    	Code c = getByCode(code);
    	return c != null ? c.getValue() : null;
    }
    
    public Code getByCode(String code){
        freshMap();
    	return codeMap.get(code);
    }

    private void freshMap(){
        if (codeMap == null){
            codeMap = new HashMap<>();
            List<Code> all = this.codeMapper.selectByExample(new CodeExample());
            for (Code code : all){
                codeMap.put(code.getCode(),code);
            }
        }
    }

    public Integer getIntegerValue(String code){
        String value = getCode(code);
        return value == null?null:Integer.valueOf(value);
    }

    public String getApiKey() {
        return null;
    }
}